package cn.melonlib.graphql.model.scalars;

import cn.hutool.core.util.ClassUtil;
import graphql.language.IntValue;
import graphql.language.Value;
import graphql.schema.*;

import java.math.BigDecimal;
import java.math.BigInteger;

import static graphql.Assert.assertNotNull;

public class GraphQLLong implements Coercing<Long,Long> {
    private static final BigInteger INT_MAX = BigInteger.valueOf(Long.MAX_VALUE);
    private static final BigInteger INT_MIN = BigInteger.valueOf(Long.MIN_VALUE);

    private GraphQLLong(){};

    private Long convertImpl(Object input) {
        if (input instanceof Number number) {
            return number.longValue();
        } else if (input instanceof CharSequence numString) {
            BigDecimal value;
            try {
                value = new BigDecimal(numString.toString());
            } catch (NumberFormatException e) {
                return null;
            }
            try {
                return value.longValueExact();
            } catch (ArithmeticException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public Long serialize(Object input) {
        Long result = convertImpl(input);
        if (result == null) {
            throw new CoercingSerializeException(
                    "Expected type 'Int' but was '" + ClassUtil.getClassName(input,true) + "'."
            );
        }
        return result;
    }

    @Override
    public Long parseValue(Object input) {
        Long result = convertImpl(input);
        if (result == null) {
            throw new CoercingParseValueException(
                    "Expected type 'Int' but was '" + ClassUtil.getClassName(input,true) + "'."
            );
        }
        return result;
    }

    @Override
    public Long parseLiteral(Object input) {
        if (!(input instanceof IntValue)) {
            throw new CoercingParseLiteralException(
                    "Expected AST type 'IntValue' but was '" + ClassUtil.getClassName(input,true) + "'."
            );
        }
        BigInteger value = ((IntValue) input).getValue();
        if (value.compareTo(INT_MIN) < 0 || value.compareTo(INT_MAX) > 0) {
            throw new CoercingParseLiteralException(
                    "Expected value to be in the Integer range but it was '" + value.toString() + "'"
            );
        }
        return value.longValue();
    }

    @Override
    public Value valueToLiteral(Object input) {
        Long result = assertNotNull(convertImpl(input));
        return IntValue.newIntValue(BigInteger.valueOf(result)).build();
    }


    private static final GraphQLScalarType graphQLScalarType=GraphQLScalarType.newScalar().name("Long").description("长整形")
            .coercing(new GraphQLLong()).build();
    public static GraphQLScalarType getLongType(){
        return graphQLScalarType;
    }
}
